//验证规则
const verifyParams = require("../verifyParams/user");
//数据库执行语句函数
const { sqlPromise } = require("../db/sqlPromise");
// 获取用户数据列表
exports.users = async (ctx) => {
  let results;
  let sql;
  if (ctx.query.query) {
    sql = "select * from sp_user where username REGEXP?";
    results = await sqlPromise(sql, ctx.query.query);
  } else {
    sql = "select * from sp_user";
    results = await sqlPromise(sql);
  }
  let mg_state = await sqlPromise("select * from sp_manager");
  let role_name = await sqlPromise("select * from sp_role");
  let dataRes = results.reduce((preVal, curVal, index) => {
    mg_state.map((item) => {
      if (item.mg_name == curVal.username) {
        curVal.mg_state = Boolean(item.mg_state);
        role_name.map((i) => {
          if (i.role_id == item.role_id) {
            curVal.role_name = i.role_name;
          }
        });
      } else {
        curVal.mg_state = false;
        curVal.role_name = "该用户不是管理员";
      }
    });
    preVal[index] = {
      id: curVal.user_id,
      mobile: curVal.user_tel,
      email: curVal.user_email,
      create_time: curVal.create_time,
      mg_state: curVal.mg_state,
      role_name: curVal.role_name,
    };
    return preVal;
  }, []);
  let data = [];

  if (dataRes.length <= ctx.query.pageszie) {
    data = dataRes;
  } else {
    for (let i = 0, j = dataRes.length; i < j; i += ctx.query.pageszie * 1) {
      data.push(dataRes.slice(i, i + ctx.query.pageszie * 1));
    }
    data = data[ctx.query.pagenum - 1];
  }
  ctx.body = {
    totalpage: results.length,
    pagenum: ctx.query.pagenum,
    users: data,
    meta: {
      msg: "获取成功",
      status: 200,
    },
  };
};
//修改用户状态
exports.modifyUserState = async (ctx) => {
  ctx.params.type == true ? (ctx.params.type = 1) : (ctx.params.type = 0);
  let res1 = await sqlPromise(
    `select * from sp_manager where mg_id=${ctx.params.uId}`
  );
  if (res1[0].mg_state == ctx.params.type) {
    console.log(1);
    ctx.body = {
      msg: "用户已是该状态",
    };
  } else {
    await sqlPromise(
      `update sp_manager set mg_state=${ctx.params.type} where mg_id=${ctx.params.uId}`
    );
    await sqlPromise(
      `select * from sp_manager where mg_id=${ctx.params.uId}`
    ).then((res) => {
      ctx.body = {
        data: {
          id: res[0].mg_id,
          rid: res[0].role_id,
          username: res[0].mg_name,
          mobile: res[0].mg_mobile,
          email: res[0].mg_email,
          mg_state: res[0].mg_state,
        },
        meta: {
          msg: "设置状态成功",
          status: 200,
        },
      };
    });
  }
};
//根据ID查询用户信息
exports.queryUser = async (ctx) => {
  await sqlPromise(
    `select * from sp_manager where mg_id=${ctx.params.id}`
  ).then((res) => {
    if (res.length) {
      ctx.body = {
        data: {
          id: res[0].mg_id,
          username: res[0].mg_name,
          role_id: res[0].role_id,
          mobile: res[0].mg_mobile,
          email: res[0].mg_email,
        },
        meta: {
          msg: "查询成功",
          status: 200,
        },
      };
    } else {
      ctx.body = {
        msg: "该用户不存在",
        status: 404,
      };
    }
  });
};
//编辑用户提交
exports.updateUser = async (ctx) => {
  let sql = "update sp_manager set mg_email=?,mg_mobile=? where mg_id=?";
  await sqlPromise(sql, [
    ctx.query.email,
    ctx.query.mobile,
    ctx.params.id,
  ]).then(async (res) => {
    if (res.affectedRows != 1) {
      ctx.body = {
        msg: "编辑用户失败",
        status: 404,
      };
    } else {
      await sqlPromise(
        `select * from sp_manager where mg_id=${ctx.params.id}`
      ).then((res) => {
        ctx.body = {
          data: {
            id: res[0].mg_id,
            username: res[0].mg_name,
            role_id: res[0].role_id,
            mobile: res[0].mg_mobile,
            email: res[0].mg_email,
          },
          meta: {
            msg: "更新成功",
            status: 200,
          },
        };
      });
    }
  });
};
//删除单个用户
exports.deleteUser = async (ctx) => {
  let sql = "delete from sp_user where user_id=?";
  await sqlPromise(sql, ctx.params.id).then((res) => {
    if (res.affectedRows != 1) {
      ctx.body = {
        msg: "删除用户失败",
        status: 404,
      };
    } else {
      ctx.body = {
        data: null,
        meta: {
          msg: "删除成功",
          status: 200,
        },
      };
    }
  });
};
//分配用户角色
exports.assignRole = async (ctx) => {
  let res1 = await sqlPromise('select * from sp_user where user_id=?',ctx.params.id)
  if(!res1.length) return ctx.body={
    msg:'未找到该用户',
    status:404
  }
  let data ={
    mg_name:res1[0].username,
    mg_pwd:res1[0].password,
    mg_time:new Date().getTime(),
    role_id:ctx.request.body.rid,
    mg_mobile:res1[0].user_tel,
    mg_email:res1[0].user_email
  }
  let sql = 'insert into sp_manager set ?'
  let res2 = await sqlPromise(sql,data)
  if(res2.affectedRows!=1) return ctx.body={
    msg:'分配角色失败',
    status:200
  }
  ctx.body = {
    data:{
      id:res2.insertId,
      rid:data.role_id,
      username:data.mg_name,
      mobile:data.mg_mobile,
      email:data.mg_email
    },
    meta:{
      msg:'分配角色成功',
      status:200
    }
  };
};
